package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wms.entity.WmsMaterial;
import org.jeecg.modules.wms.mapper.WmsMaterialMapper;
import org.jeecg.modules.wms.service.IWmsMaterialService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 物料基础信息Service实现类
 */
@Service
@Slf4j
public class WmsMaterialServiceImpl extends ServiceImpl<WmsMaterialMapper, WmsMaterial> implements IWmsMaterialService {

    @Override
    public List<WmsMaterial> listByType(String materialType) {
        LambdaQueryWrapper<WmsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(materialType)) {
            queryWrapper.eq(WmsMaterial::getMaterialType, materialType);
        }
        queryWrapper.eq(WmsMaterial::getStatus, "0"); // 只查询启用状态的
        queryWrapper.orderByAsc(WmsMaterial::getMaterialCode);
        return this.list(queryWrapper);
    }

    @Override
    public List<WmsMaterial> listAll(Map<String, Object> params) {
        LambdaQueryWrapper<WmsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        
        // 物料类型过滤
        String materialType = (String) params.get("materialType");
        if (StringUtils.isNotBlank(materialType)) {
            queryWrapper.eq(WmsMaterial::getMaterialType, materialType);
        }
        
        // 状态过滤
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(WmsMaterial::getStatus, status);
        } else {
            queryWrapper.eq(WmsMaterial::getStatus, "0"); // 默认只查询启用状态的
        }

        // 关键字搜索（物料编号或名称）
        String keyword = (String) params.get("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> 
                wrapper.like(WmsMaterial::getMaterialCode, keyword)
                       .or()
                       .like(WmsMaterial::getMaterialName, keyword)
            );
        }
        
        queryWrapper.orderByAsc(WmsMaterial::getMaterialCode);
        return this.list(queryWrapper);
    }
    
    @Override
    public WmsMaterial getByCode(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        LambdaQueryWrapper<WmsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmsMaterial::getMaterialCode, code);
        queryWrapper.eq(WmsMaterial::getStatus, "0"); // 只查询启用状态的
        return this.getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> importExcel(MultipartFile file, String materialType, HttpServletRequest request) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setNeedSave(true);
        
        try {
            List<WmsMaterial> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsMaterial.class, params);
            // 设置物料类型
            for (WmsMaterial material : list) {
                if (StringUtils.isBlank(material.getMaterialType())) {
                    material.setMaterialType(materialType);
                }
                if (StringUtils.isBlank(material.getStatus())) {
                    material.setStatus("0"); // 默认启用状态
                }
                // 校验数据
                String message = validateMaterial(material);
                if (StringUtils.isNotBlank(message)) {
                    return Result.error("导入失败：" + message);
                }
            }
            this.saveBatch(list);
            return Result.ok("导入成功！共导入" + list.size() + "条数据");
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 校验物料数据
     * @param material 物料数据
     * @return 校验不通过返回错误信息，通过返回null
     */
    private String validateMaterial(WmsMaterial material) {
        // 校验必填字段
        if (StringUtils.isBlank(material.getMaterialCode())) {
            return "物料编号不能为空";
        }
        if (StringUtils.isBlank(material.getMaterialName())) {
            return "物料名称不能为空";
        }
        if (StringUtils.isBlank(material.getMaterialType())) {
            return "物料类型不能为空";
        }
        if (StringUtils.isBlank(material.getUnit())) {
            return "单位不能为空";
        }
        
        // 校验编号唯一性
        LambdaQueryWrapper<WmsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmsMaterial::getMaterialCode, material.getMaterialCode());
        if (StringUtils.isNotBlank(material.getId())) {
            queryWrapper.ne(WmsMaterial::getId, material.getId());
        }
        long count = this.count(queryWrapper);
        if (count > 0) {
            return "物料编号[" + material.getMaterialCode() + "]已存在";
        }
        
        return null;
    }
} 